package com.wzdigit.wms.raw.client.request.initialize.test;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.GdnDtlStatusEnum;
import com.wzdigit.wms.basic.enums.GdnHeaderStatusEnum;
import com.wzdigit.wms.basic.enums.GdnTypeEnum;
import com.wzdigit.wms.basic.enums.QaStatusEnum;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnHeaderMapper;
import com.wzdigit.wms.raw.mapper.initialize.InitializeReportMapper;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by zyf on 2021/8/30 21:48
 */
@Service
public class AsnImportInsertService {
    @Autowired
    private GdnHeaderMapper gdnHeaderMapper;
    @Autowired
    private GdnDtlMapper gdnDtlMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private InitializeReportMapper initializeReportMapper;
    @Autowired
    private SkuMapper skuMapper;

    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi basicVendorApi;

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void tryInsertGdn(List<AsnInmportRequest> dtoList) throws Exception {
        String str="";
        for (AsnInmportRequest asnInmportRequest : dtoList) {
            str=str+asnInmportRequest.getRow()+"、";
        }
        AsnInmportRequest dto=dtoList.get(0);
        if (dto.getGdnNo()==null){
            throw new Exception(str+"采购单号为空!");
        }
        if (dto.getVendorCode()==null){
            throw new Exception(str+"行供应商编码为空!");
        }
        VendorDTO vendor = basicVendorApi.getVendorByCode(dto.getVendorCode());
        if (vendor == null||vendor.getVendorId()==null) {
            throw new Exception(str+"行供应商查无信息!");
        }
        if (dto.getCreateUser()==null){
            throw new Exception(str+"行创建人为空!");
        }
        if (dto.getCreateTimeStr()==null){
            throw new Exception(str+"行创建时间为空!");
        }
        if (dto.getFactory()==null){
            throw new Exception(str+"行工厂为空!");
        }
        Date createTime = stringChangeDate(dto.getCreateTimeStr());
        if (createTime==null){
            throw new Exception(str+"行创建时间格式错误!");
        }
        GdnHeader gdnHeader=new GdnHeader();
        GdnHeader gdnHeaderSearch = gdnHeaderMapper.selectOne(new QueryWrapper<GdnHeader>().eq("GDN_NO", dto.getGdnNo()));
        if (gdnHeaderSearch==null){
            gdnHeader.setGdnNo(dto.getGdnNo());
            gdnHeader.setGdnType(GdnTypeEnum.D18.code);
            gdnHeader.setConsigneeId(vendor.getVendorId().longValue());
            gdnHeader.setConsigneeName(vendor.getVendorName());
            gdnHeader.setGdnCreateUser(dto.getCreateUser());
            gdnHeader.setGdnCreateTime(createTime);
            gdnHeader.setFactory(dto.getFactory());
            gdnHeader.setShipDate(new Date());
            gdnHeader.setStatus(GdnHeaderStatusEnum.CREATE.getCode());//新建状态
            gdnHeader.setCreateUser(dto.getCreateUser());
            gdnHeader.setCreateTime(createTime);
            gdnHeader.setOwner(10001);
            gdnHeaderMapper.insert(gdnHeader);
        }else {
            gdnHeader.setModifyTime(new Date());
            gdnHeader.setModifyUser("system");
            gdnHeader.setGdnHeaderId(gdnHeaderSearch.getGdnHeaderId());
            gdnHeaderMapper.updateById(gdnHeader);
        }
        for (AsnInmportRequest dtlDto : dtoList) {
            if (dtlDto.getGdnLineNoStr()==null){
                throw new Exception(dtlDto.getRow()+"行采购单行号为空!");
            }
            if (!checkStrIsNum(dtlDto.getGdnLineNoStr())){
                throw new Exception(dtlDto.getRow()+"行采购单行号必须为数字!");
            }
           /* if (dtlDto.getErpCode()==null){
                throw new Exception(dtlDto.getRow()+"行库位为空!");
            }
            List<String> whsCodeList = initializeReportMapper.selectMappingWhs(dtlDto.getErpCode(), dto.getFactory(), 2);
            if (CollectionUtil.isEmpty(whsCodeList)){
                throw new Exception(dtlDto.getRow()+"查无仓库映射!");
            }else if (whsCodeList.size()>1){
                throw new Exception(dtlDto.getRow()+"仓库映射存在重复数据!");
            }
            Warehouse warehouse = warehouseMapper.selectOne(new QueryWrapper<Warehouse>().eq("WHS_CODE", whsCodeList.get(0)));
            if (warehouse==null){
                throw new Exception(dtlDto.getRow()+"没有配置WMS仓库信息!");
            }*/
            if (dtlDto.getSkuCode()==null){
                throw new Exception(dtlDto.getRow()+"行物料编码为空!");
            }
            Sku sku = skuMapper.selectOne(new QueryWrapper<Sku>().eq("SKU_CODE", dtlDto.getSkuCode()));
            if (sku==null){
                throw new Exception(dtlDto.getRow()+"没有配置WMS物料信息!物料编码:"+dtlDto.getSkuCode());
            }
            if (dtlDto.getOrderQtyStr()==null){
                throw new Exception(dtlDto.getRow()+"行订单数量为空!");
            }
            if (!checkStrIsNum(dtlDto.getOrderQtyStr())){
                throw new Exception(dtlDto.getRow()+"行订单数量必须为数字!");
            }
            if (dtlDto.getRcvTimeStr()==null){
                throw new Exception(dtlDto.getRow()+"行交货日期为空!");
            }
            Date rcvDate = stringChangeDate(dtlDto.getRcvTimeStr());
            if (rcvDate==null){
                throw new Exception(dtlDto.getRow()+"行交货日期格式错误!");
            }
            GdnDtl gdnDtlSearch = gdnDtlMapper.selectOne(new QueryWrapper<GdnDtl>().eq("GDN_HEADER_ID", gdnHeader.getGdnHeaderId()).eq("GDN_LINE_NO", Integer.valueOf(dtlDto.getGdnLineNoStr())));
            if (gdnDtlSearch!=null){
                throw new Exception(dtlDto.getRow()+"行存在重复数据!");
            }
            GdnDtl gdnDtl=new GdnDtl();
            gdnDtl.setGdnHeaderId(gdnHeader.getGdnHeaderId());

            gdnDtl.setSkuId(sku.getSkuId());
            gdnDtl.setOrderQty(new BigDecimal(dtlDto.getOrderQtyStr()));
            gdnDtl.setUnit(sku.getBaseUnit());
            gdnDtl.setCreateTime(createTime);
            gdnDtl.setCreateUser(dto.getCreateUser());
            gdnDtl.setStatus(GdnDtlStatusEnum.CREATE.getCode());//新建状态
            gdnDtl.setGdnLineNo(Integer.valueOf(dtlDto.getGdnLineNoStr()));//设置自定义行号
            gdnDtl.setQaStatus(QaStatusEnum.NG.code);
            gdnDtlMapper.insert(gdnDtl);
        }
    }

    //判断字符串是否为数字
    public static boolean checkStrIsNum(String str) {
        String bigStr;
        try {
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    private Date stringChangeDate(String value) {
        Date date = null;
        try {
            if (value.length() <= 5) {
                date = HSSFDateUtil.getJavaDate(Double.parseDouble(value));
                return date;
            }
            if (value.trim().contains("/")) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
                date = simpleDateFormat.parse(value);
            } else if (value.trim().contains("-")) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                date = simpleDateFormat.parse(value);
            } else if (value.trim().contains(".")) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
                date = simpleDateFormat.parse(value);
            } else if (value.trim().contains("年") && value.trim().contains("月") && value.trim().contains("日")) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
                date = simpleDateFormat.parse(value);
            } else if (value.trim().contains("年") && value.trim().contains("月")) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd");
                date = simpleDateFormat.parse(value);
            } else {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                date = simpleDateFormat.parse(value);
            }
        } catch (Exception ex) {
            return date;
        }
        return date;
    }
}
